package com.english.service;

import com.english.util.AuthV3Util;
import com.english.util.FileUtil;
import com.english.util.HttpUtil;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易有道智云语音合成服务api调用demo
 * api接口: https://openapi.youdao.com/ttsapi
 */
public class TtsDemo {

    private static final String APP_KEY = "520de8df2e0bbb47";     // 您的应用ID
    private static final String APP_SECRET = "gDeetB0FbsUvPKp6cx8REzOlBboqV5L7";  // 您的应用密钥

    // 合成音频保存路径, 例windows路径：PATH = "C:\\tts\\media.mp3";
    public static final String PATH = "C:\\Users\\Administrator\\Desktop\\tts\\media.mp3";

    public static void test(String txt,String speaker) throws NoSuchAlgorithmException, IOException {
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(txt,speaker);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/ttsapi", null, params, "audio");
        // 打印返回结果
        if (result != null) {
            String path = FileUtil.saveFile(PATH, result, false);
            System.out.println("save path:" + path);
        }
    }

    private static Map<String, String[]> createRequestParams(String txt,String speaker) {
        /*
         * note: 将下列变量替换为需要请求的参数
         */
        String voiceName = null;
        String q = txt;
        if (speaker.equals("1")) {
            voiceName = "youxiaomei";//美式女声
        } else if (speaker.equals("2")) {
            voiceName = "youxiaowei";//美式男声
        } else if (speaker.equals("3")) {
            voiceName = "youxiaoying";//英式女声
        } else if (speaker.equals("4")) {
            voiceName = "youxiaoguan";//英式男声
        }

        String format = "mp3";

        String finalVoiceName = voiceName;
        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("voiceName", new String[]{finalVoiceName});
            put("format", new String[]{format});
        }};
    }
}
